import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:dear_lottery/Statistics/views/DL_ChooseTicketNumbers.dart';
import 'package:dear_lottery/tools/models/DL_DataViewModel.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../tools/DL_Config.dart';
import '../tools/DL_Segment.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'views/KL_digitView.dart';

class DlAnalyticspagevc extends StatefulWidget {
  const DlAnalyticspagevc({super.key});

  @override
  State<DlAnalyticspagevc> createState() => _DlAnalyticspagevcState();
}

class _DlAnalyticspagevcState extends State<DlAnalyticspagevc>
    with AutomaticKeepAliveClientMixin {
  ///保存选号到数据库
  MyTicketEntity _ticketEntity = MyTicketEntity.instan();

  int _currentTypeIndex = 0; //
  //选中号码数组
  late var _selectedNumbers = [];

  late List _draws_titles_left = []; //左边日期

  double _rightSideWidth = 0;
  double _leftSideWidth = 80; //左边宽度
  double _cellHeight = 40; //cell高度
  double _cellWidth = 25; //cell宽度

  final ScrollController _formContentController = ScrollController();
  final ScrollController _headerDigitsController = ScrollController();
  final ScrollController _formNumsContentController = ScrollController();

  var _digitStr = []; //头部view多少parts
  var _headerDigitsDatas = []; //组装头部View数据
  late var _formContentDigitsDatas = []; //组装右边View，开奖号码数据

  ///save to checker
  _EJ_saveTpChecker() async {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });

    var _saveNumbers = [];
    for (Map element in _selectedNumbers) {
      var number = element['num'];
      _saveNumbers.add(number);
    }

    if (_saveNumbers.isEmpty) {
      BotToast.closeAllLoading();
      return;
    } else if (_saveNumbers.length < DL_Config.digitsStringArr.length) {
      BotToast.closeAllLoading();
      BotToast.showText(
          textStyle: const TextStyle(fontSize: 13, color: Colors.white),
          text: 'Please select ${DL_Config.digitsStringArr.length} numbers');
      return;
    }

    //补全号码
    // var ticketFirstNum = KL_keralaLottoDataModel().nextDrawnModel.ticket_prefix;
    // _saveNumbers.insert(0, ticketFirstNum);

    // 获取当前时间戳（毫秒）
    int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
    var tickets = {
      "name": "Lucky Number",
      "time": currentTimeMillis,
      "numbers": jsonEncode(_saveNumbers),
    };

    ///保存选号
    // int save = await ticketEntity.insert(tickets);
    await _ticketEntity.insert(tickets);
    Future.delayed(const Duration(milliseconds: 300), () {
      BotToast.closeAllLoading();
      BotToast.showText(text: 'Save successfully!');
    });
  }

  ///砌头部数据和view
  _configHeaderDatas() async {
    var firstNumDigits = DL_Config.FirstNumDigits;
    var secondNumDigits = DL_Config.otherDigitNums;
    var digitLetters = DL_Config.DigitLetters;
    var otherDigitNums = DL_Config.otherDigitNums;
    _headerDigitsDatas.clear();
    for (var i = 0; i < _digitStr.length; i++) {
      var digitStr = _digitStr[i];
      if (i == 0) {
        Map firstDigitMap = {
          'title': '$digitStr Digit',
          'nums': firstNumDigits
        };
        _headerDigitsDatas.add(firstDigitMap);

        ///计算右边表格总宽度
        _rightSideWidth += firstNumDigits.length * _cellWidth;
      } else if (i == 1) {
        Map secondDigitMap = {
          'title': '$digitStr Digit',
          'nums': secondNumDigits
        };
        _headerDigitsDatas.add(secondDigitMap);

        ///计算右边表格总宽度
        _rightSideWidth += secondNumDigits.length * _cellWidth;
      } else if (i == 2) {
        Map letterDigitMap = {'title': '$digitStr Digit', 'nums': digitLetters};
        _headerDigitsDatas.add(letterDigitMap);

        ///计算右边表格总宽度
        _rightSideWidth += digitLetters.length * _cellWidth;
      } else {
        Map digitMap = {'title': '$digitStr Digit', 'nums': otherDigitNums};
        _headerDigitsDatas.add(digitMap);

        ///计算右边表格总宽度
        _rightSideWidth += otherDigitNums.length * _cellWidth;
      }
    }
    debugPrint('_headerDigitsDatas: $_headerDigitsDatas');
    setState(() {});
  }

  _onTabChanged(int index) {
    _configDrawsTitlesLeft(index);
  }

  ///左边日期
  _configDrawsTitlesLeft(int index) async {
    _draws_titles_left.clear();
    _draws_titles_left = await DL_DataViewModel().getPMTypeDrawnDate(index);
    debugPrint('_draws_titles_left: $_draws_titles_left');
    if (_draws_titles_left.isNotEmpty) {
      await _configFormDatas(index);
      setState(() {
        //自动滑动到最底
        Future.delayed(const Duration(milliseconds: 300), () {
          BotToast.closeAllLoading();
          _formContentController
              .jumpTo(_formContentController.position.maxScrollExtent);
        });
        // Future.delayed(const Duration(milliseconds: 300), () {
        //   BotToast.closeAllLoading();
        // });
      });
    } else {
      setState(() {});
    }
  }

  ///右边表格数据
  _configFormDatas(int index) async {
    _formContentDigitsDatas =
        await DL_DataViewModel().DL_getAnalyticsResults(index);
    debugPrint('_formContentDigitsDatas: $_formContentDigitsDatas');
  }

  _updateFormContentController() {
    print('formContentController: ${_formContentController.offset}');
  }

  _updateHeaderDigitsController() {
    print('headerDigitsController: ${_headerDigitsController.offset}');
    if (_headerDigitsController.offset != _formNumsContentController.offset) {
      _headerDigitsController.jumpTo(_formNumsContentController.offset);
    }
  }

  _updateFormNumsContentController() {
    print('formNumsContentController: ${_formNumsContentController.offset}');
    if (_formNumsContentController.offset != _headerDigitsController.offset) {
      _formNumsContentController.jumpTo(_headerDigitsController.offset);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //分区个数
    _digitStr = DL_Config.digitsStringArr;

    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading(
        title: 'loading...',
      );
    });

    _configHeaderDatas();

    // 延时 0.1 秒后执行的操作
    Future.delayed(const Duration(milliseconds: 100), () {
      _configDrawsTitlesLeft(_currentTypeIndex);
    });

    ///监听滑动联动
    _headerDigitsController.addListener(_updateFormNumsContentController);
    _formNumsContentController.addListener(_updateHeaderDigitsController);
    _formContentController.addListener(_updateFormContentController);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _headerDigitsController.removeListener(_updateFormNumsContentController);
    _formNumsContentController.removeListener(_updateHeaderDigitsController);
    _headerDigitsController.dispose();
    _formContentController.dispose();
    _formNumsContentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        backgroundColor: DL_Config.DL_MainColor,
        foregroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Container(
        color: DL_Config.DL_pageBgColor,
        child: Column(children: [
          segmentView(),
          Expanded(
              child: Container(
            color: DL_Config.DL_pageBgColor,
            child: _draws_titles_left.isEmpty
                ? noDataView()
                : Column(
                    children: [
                      formView(),
                      bottomView(),
                    ],
                  ),
          )),
        ]),
      ),
    );
  }

  Widget noDataView() {
    return Container(
      child: Center(
          child: Text(
        'No Data',
      )),
    );
  }

  Widget formView() {
    return Expanded(
      child: Stack(
        alignment: Alignment.topLeft,
        children: [
          Column(
            children: [
              formHeaderView(),
              formContentView(),
            ],
          ),
        ],
      ),
    );
  }

  Widget formHeaderView() {
    return Row(children: [
      drawsView(),
      headerDigitsView(),
    ]);
  }

  Widget formContentView() {
    return Expanded(
      child: CustomScrollView(
        physics: const ClampingScrollPhysics(), //禁止惯性
        controller: _formContentController,
        slivers: [
          SliverToBoxAdapter(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                // 自定义左侧列表的宽度
                Container(
                  color: Colors.white,
                  width: _leftSideWidth, // 设置左侧列表宽度
                  child: buildContentLeftList(),
                ),

                // 自定义右侧列表的宽度
                Expanded(
                  child: SingleChildScrollView(
                    controller: _formNumsContentController,
                    physics: const ClampingScrollPhysics(), //禁止惯性
                    scrollDirection: Axis.horizontal,
                    child: SizedBox(
                      width: _rightSideWidth, // 设置右侧列表的宽度
                      child: buildContentRightList(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget buildContentRightList() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      physics: const NeverScrollableScrollPhysics(), // 禁止滚动
      shrinkWrap: true, // 适应高度
      itemCount: _formContentDigitsDatas.length,
      itemBuilder: (context, index) {
        bool isLastLine = index == _formContentDigitsDatas.length - 1;
        if (!isLastLine) {
          return rightSideView(index, isLastLine: isLastLine);
        } else {
          List digitsDatas = _formContentDigitsDatas[index];
          return DlChooseticketnumbers(
            key: ValueKey(index),
            numberDatas: digitsDatas,
            callback: (selectedNumber) {
              print('选中---$selectedNumber');
              _selectedNumbers.clear();
              for (List element in selectedNumber.values) {
                if (element.isNotEmpty) {
                  _selectedNumbers.addAll(element);
                }
              }
              setState(() {});
            },
          );
        }
      },
    );
  }

  Widget buildContentLeftList() {
    return ListView.builder(
      physics: const NeverScrollableScrollPhysics(), // 禁止滚动
      shrinkWrap: true, // 适应高度
      itemCount: _draws_titles_left.length,
      itemBuilder: (context, index) {
        bool isLastLine = index == _draws_titles_left.length - 1;
        return leftSideItem(_draws_titles_left[index], isLastLine);
      },
    );
  }

  Widget headerDigitsView() {
    return Expanded(
      child: Container(
        color: Colors.yellow,
        width: _rightSideWidth,
        height: _cellHeight * 2,
        child: ListView.builder(
            controller: _headerDigitsController,
            physics: const ClampingScrollPhysics(),
            scrollDirection: Axis.horizontal,
            itemCount: _headerDigitsDatas.length,
            itemBuilder: (context, index) {
              var data = _headerDigitsDatas[index];
              return KlDigitview(digitMap: data);
            }),
      ),
    );
  }

  Widget rightSideView(int index, {bool isLastLine = false}) {
    List digitsDatas = _formContentDigitsDatas[index];
    List<Widget> _rowViews = [];
    for (int i = 0; i < digitsDatas.length; i++) {
      Map element = digitsDatas[i];
      List _numbers = element['nums'] ?? [];

      int oddIndex = i % 2;
      Color bgColor = oddIndex == 0 ? HexColor('#e6fff0') : HexColor('#ffecf5');
      Color rightNumColor =
          oddIndex == 0 ? HexColor('#168a43') : HexColor('#d22f7d');

      ///
      _rowViews.add(KlDigitview(
        key: ValueKey(_numbers[i]),
        digitMap: element,
        isTheLast: isLastLine,
        bgColor: bgColor,
        rightNumColor: rightNumColor,
      ));
    }
    return Wrap(
      children: _rowViews,
    );
  }

  Widget leftSideItem(String title, bool isLastLine) {
    Alignment alignment = Alignment.center;
    double viewH = _cellHeight;
    double _titleOffset = 0;
    if (isLastLine) {
      alignment = Alignment.topCenter;
      viewH = viewH * 2;
      _titleOffset = 8.0;
    }
    return Container(
      alignment: alignment,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
          right: BorderSide(color: HexColor('#dddddd'), width: 1),
        ),
        // color: Colors.white,
      ),
      width: _cellWidth,
      height: viewH,
      child: Padding(
        padding: EdgeInsets.only(top: _titleOffset),
        child: Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  Widget drawsView() {
    return Container(
      width: _leftSideWidth,
      height: _cellHeight * 2,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: HexColor('#dddddd'), width: 1),
          right: BorderSide(color: HexColor('#dddddd'), width: 1),
          bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
        ),
      ),
      child: const Text('Draws',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.w400,
            fontSize: 12,
          )),
    );
  }

  Widget segmentView() {
    return Container(
      width: double.infinity,
      height: 40,
      color: Colors.white,
      child: SizedBox(
        height: 40,
        child: Padding(
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: DlSegment(
            sliderColor: HexColor('#ff3433'),
            onSegmentChange: (index, value) => {
              debugPrint('value---$value,index---$index'),
              _currentTypeIndex = index,
              _onTabChanged(index),
            },
          ),
        ),
      ),
    );
  }

  Widget bottomView() {
    var number = '';
    for (var element in _selectedNumbers) {
      var num = element['num'];
      number += '$num';
    }

    return Container(
      height: 45,
      color: Colors.white,
      child: Row(
        children: [
          const SizedBox(width: 15),
          Text(
            'Choose numbers ($number)',
            style: const TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w400,
            ),
          ),
          const Spacer(),
          OutlinedButton(
            onPressed: () {
              debugPrint('Save to Checker');
              _EJ_saveTpChecker();
            },
            style: ButtonStyle(
                backgroundColor: WidgetStatePropertyAll(DL_Config.DL_MainColor),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                side: WidgetStateProperty.all(
                    //边框
                    BorderSide(
                  color: DL_Config.DL_MainColor, //颜色
                  width: 1.0, //宽度
                )),
                minimumSize: const WidgetStatePropertyAll(Size(40, 35))),
            child: const Text(
              "Save to Checker",
              style: TextStyle(fontWeight: FontWeight.w400, fontSize: 13),
            ),
          ),
          const SizedBox(width: 15),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
